#!/usr/bin/env python
# $Id: testwhois.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"
 
import optparse
import re
import sys
import urllib2
from xml.dom.minidom import parse, parseString

from venya.lib import cmdparser
import wholib

class whois(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-p", "--port", default = 43, type = "int",
            help = "whois port: default: 43",
            dest = "port"),
         optparse.make_option("-a", "--as", action = "store_true",
            help = "Get AS number information for whois.ra.net",
            default = False, dest = "asn"),
         optparse.make_option("-r", "--rest", action = "store_true",
            help = "Use RESTful ARIN request", default = False, dest = "rest"),
         optparse.make_option("-s", "--server", default = 'whois.arin.net',
            type = "choice", choices = ['whois.lacnic.net',
               'whois.apnic.net',
               'whois.afrinic.net',
               'whois.arin.net',
               'whois.ripe.net'],
            help = "Whois server to use, default: whois.arin.net")
         ) + cmdparser.GetOpt.option_list

   def __init__(self, **Keywords):
      self._asn = "http://www.iana.org/assignments/as-numbers/as-numbers.xml"
      self._ipv4 = "http://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xml"
      self._servers = {
            'afrnic' : 'whois.afrinic.net',
            'apnic'  : 'whois.apnic.net',
            'arin'   : 'whois.arin.net',
            'lacnic' : 'whois.lacnic.net',
            'ripe'   : 'whois.ripe.net',
            }

      super(self.__class__, self).__init__(**Keywords)

   def handle(self):
      (options, args) = self.parse()
      entry = None
      try:
         entry = args[1]
      except IndexError, message:
         self.error("Need host or as number!")
      else:
         asList = []
         urldata = urllib2.urlopen(self._asn)
         dom = parseString(urldata.read())
         for node in dom.getElementsByTagName('record'):
            server = None
            info = None
            asn = node.getElementsByTagName('number')[0].firstChild.nodeValue
            whois = node.getElementsByTagName('whois')
            if whois:
               server = whois[0].firstChild.nodeValue

            desc = node.getElementsByTagName('description')
            if desc:
               info = desc[0].firstChild.nodeValue

            asList.append(wholib.asn(asn, server, info))

         """
         for node in asList:
            if entry in node:
               print node.info(entry)
         """

         ipList = []
         urldata = urllib2.urlopen(self._ipv4)
         dom = parseString(urldata.read())
         for node in dom.getElementsByTagName('record'):
            server = None
            ipnet = node.getElementsByTagName('prefix')[0].firstChild.nodeValue
            whois = node.getElementsByTagName('whois')
            if whois:
               server = whois[0].firstChild.nodeValue

            print(ipnet, server)
            ipList.append(wholib.ipv4Net(ipnet, server))

         for node in ipList:
            if entry in node:
               print node.info(entry)

if __name__ == "__main__":
   wsclient = None
   try:
      wsclient = whois(version = 1.0, args = sys.argv, usage = "[ host ]")
      if len(wsclient) <= 1:
         wsclient.printhelp()
      else:
         wsclient.handle()
   except cmdparser.GetOptError, message:
      print message
      sys.exit(1)
